package com.woniuxy.gateway.service;

import com.woniuxy.cloud.api.UserQueryAPI;
import com.woniuxy.cloud.api.dto.LoginDto;

import com.woniuxy.gateway.entity.AuthUserDetails;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

@Service
public class SecurityUserDetailService implements ReactiveUserDetailsService {
    private final PasswordEncoder passwordEncoder;

    @Resource
    private UserQueryAPI userQueryAPI;

    public SecurityUserDetailService(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public Mono<UserDetails> findByUsername(String username) {
        LoginDto dto = userQueryAPI.login(username);
        if (null == dto || dto.getUserId() == null) {
            throw new UsernameNotFoundException("没有此账号");
        }
        AuthUserDetails userTableDetails = new AuthUserDetails();

        BeanUtils.copyProperties(dto, userTableDetails);

        return Mono.just(userTableDetails);
    }
}
